<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>订单管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="danger"
          class="handle-del mr10"
          @click="batchDeleteHandler"
          >批量删除</el-button
        >
        <el-input
          placeholder="筛选关键词"
          class="handle-input mr10"
          v-model="value"
          clearable
          autofocus
          @clear="inputClearHandler"
          @keyup.enter.native="inputKeyupHandler"
        ></el-input>
        <el-button type="primary" @click="searchClickHandler">搜索</el-button>
        <el-button type="primary" @click="handlerDownloadALL"
          >导出{{
            orderList.length === oldOrderList.length ? "全部" : "筛选结果"
          }}</el-button
        >
      </div>
      <el-table
        border
        stripe
        class="table"
        :data="
          orderList.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
      >
        <el-table-column
          type="selection"
          width="56"
          align="center"
        ></el-table-column>
        <el-table-column label="订单号" width="144" align="center">
          <template slot-scope="scope">
            <p class="order-text">{{ scope.row.id }}</p>
          </template>
        </el-table-column>
        <el-table-column label="下单时间" width="88" align="center">
          <template slot-scope="scope">
            <p class="order-text">{{ scope.row.time }}</p>
          </template>
        </el-table-column>
        <el-table-column label="商品信息" min-width="102" align="center">
          <template slot-scope="scope">
            <p class="order-text">商品标题: {{ scope.row.goodsInfo.title }}</p>
          </template>
        </el-table-column>
        <el-table-column label="用户信息" width="136" align="center">
          <template slot-scope="scope">
            <p class="order-text">姓名: {{ scope.row.userInfo.username }}</p>
            <p class="order-text">手机: {{ scope.row.userInfo.tel }}</p>
            <p class="order-text">地址: {{ scope.row.userInfo.address }}</p>
          </template>
        </el-table-column>
        <el-table-column label="支付信息" width="125" align="center">
          <template slot-scope="scope">
            <p class="order-text">
              金额:
              <span style="color: red;font-weight: bold">{{
                scope.row.payInfo.money
              }}</span>
            </p>
            <p class="order-text">付款: {{ scope.row.payInfo.method }}</p>
            <p class="order-text">状态: {{ scope.row.payInfo.isPay }}</p>
          </template>
        </el-table-column>
        <el-table-column label="物流信息" min-width="102" align="center">
          <template slot-scope="scope">
            <p class="order-text">快递: {{ scope.row.logisticsInfo.type }}</p>
            <p class="order-text">
              单号:
              <el-button
                type="text"
                @click="logisticsClickHandler(scope.row)"
                >{{ scope.row.logisticsInfo.id }}</el-button
              >
            </p>
            <p class="order-text">状态: {{ scope.row.logisticsInfo.status }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >详情</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="orderList.length"
          :page-size="pageSize"
          :page-sizes="[3, 5, 10, 20, 50]"
          :current-page="currentPage"
          @size-change="sizeChangeHandler"
          @current-change="currentChangeHandler"
        ></el-pagination>
      </div>
      <!-- 详情框 -->
      <el-dialog
        title="详细信息"
        :visible.sync="editUserVisible"
        ref="editUserForm"
        v-dialogDrag
        v-if="ordersForm"
      >
        <el-form ref="editUserForm">
          <el-form-item label="编号:" :label-width="formLabelWidth">
            <template>
              <p>{{ ordersForm.id }}</p>
            </template>
          </el-form-item>
          <el-form-item label="下单时间:" :label-width="formLabelWidth">
            <template>
              <p>{{ ordersForm.time }}</p>
            </template>
          </el-form-item>
          <el-form-item label="商品信息:" :label-width="formLabelWidth">
            <template>
              <p>{{ ordersForm.goodsInfo.title }}</p>
            </template>
          </el-form-item>
          <el-form-item label="用户信息:" :label-width="formLabelWidth">
            <template>
              <p>{{ ordersForm.userInfo.username }}</p>
              <p>{{ ordersForm.userInfo.tel }}</p>
              <p>{{ ordersForm.userInfo.address }}</p>
            </template>
          </el-form-item>
          <el-form-item label="支付信息:" :label-width="formLabelWidth">
            <template>
              <p style="color: red">{{ ordersForm.payInfo.money }}</p>
              <p>{{ ordersForm.payInfo.method }}</p>
              <p>{{ ordersForm.payInfo.isPay }}</p>
            </template>
          </el-form-item>
          <el-form-item label="物流信息:" :label-width="formLabelWidth">
            <template>
              <p>{{ ordersForm.logisticsInfo.type }}</p>
              <p>
                <el-button
                  type="text"
                  @click="logisticsClickHandler(ordersForm)"
                  >{{ ordersForm.logisticsInfo.id }}</el-button
                >
              </p>
              <p>{{ ordersForm.logisticsInfo.status }}</p>
            </template>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editUserVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserVisible = false"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <el-dialog
        title="物流详情"
        :visible.sync="logisticsInfoVisible"
        ref="logisticsForm"
        v-dialogDrag
      >
        <el-form ref="logisticsForm" v-if="logisticsForm.logisticsInfo">
          <p>物流公司: {{ logisticsForm.logisticsInfo.type }}</p>
          <p>快递单号: {{ logisticsForm.logisticsInfo.id }}</p>
          <br />
          <div style="height: 300px;">
            <el-steps direction="vertical" :active="2">
              <el-step title="卖家发货"></el-step>
              <el-step title="物流中心分拣快递"></el-step>
              <el-step
                title="运输中"
                description="你的包裹半路被烧了"
              ></el-step>
              <el-step title="等待签收"></el-step>
            </el-steps>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="logisticsInfoVisible = false"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getOrderList } from "../../../api/api";
import Vue from "vue";
import { Select, Option } from "element-ui";
import Xlsx from "xlsx";

Vue.use(Select);
Vue.use(Option);

export default {
  data() {
    return {
      orderList: [],
      oldOrderList: [],
      editUserVisible: false,
      ordersForm: null,
      formLabelWidth: "120px",
      logisticsInfoVisible: false,
      pageSize: 3,
      currentPage: 1,
      value: "",
      options: [],
      searchStr: "",
      logisticsForm: {}
    };
  },
  created() {
    getOrderList().then(result => {
      result.map(item => {
        item.payInfo.money = item.payInfo.money.toFixed(2);
        item.payInfo.isPay = item.payInfo.isPay ? "已付款" : "未付款";
        // 初始化拼接的搜索字符串
        this.searchStr = "";
        // 执行递归遍历函数,把每一个对象数据带进去
        this.recursiveData(item);
        // 给每个对象数据新增一个search属性,值为拼接的搜索字符串
        // 目的是为了在搜索的时候,直接在search属性里面查询是否存在
        item.search = this.searchStr;
      });
      this.orderList = result;
      // 将原始数据存储在oldOriderList,因为搜索过后,需要筛选数组且渲染页面
      // 这样将会改变原数组,那么再次搜索或者还原,就不能得到原始数据,所以存储起来
      this.oldOrderList = this.orderList;
    });
  },
  methods: {
    // 递归累加需要搜索的字符串
    recursiveData(data) {
      for (let value in data) {
        // 查看带入的数据的属性值的类型
        switch (typeof data[value]) {
          case "object":
          case "array":
            // 如果属性值是对象或者数组,那么就将属性值作为参数再次递归
            // 深度遍历
            this.recursiveData(data[value]);
            break;
          case "number":
            data[value] = data[value].toString();
            break;
          default:
            // 将所有属性值拼接在searchStr变量中
            // 在created钩子函数中就会给每个对象添加search属性,值为拼接结果
            this.searchStr += data[value] + ",";
        }
      }
    },
    // TODO:物流查询
    logisticsClickHandler(row) {
      this.logisticsInfoVisible = true;
      this.logisticsForm = Object.assign({}, row);
    },
    // 点击编辑按钮的事件
    handleEdit(index, row) {
      // 编辑框显示
      this.editUserVisible = true;
      this.ordersForm = Object.assign({}, row);
    },
    // 删除
    handleDelete(index, row) {
      this.$confirm("确认删除该用户？", "提示", {
        type: "warning"
      })
        .then(() => {
          // 这里可能是在搜索之后进行删除,所以无论什么情况,orderList和存储原始数据的oldOrderList都得删除该项
          this.orderList = this.orderList.filter(item => item.id !== row.id);
          this.oldOrderList = this.oldOrderList.filter(
            item => item.id !== row.id
          );
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          // 处理错误程序,点击取消时会将Promise的状态从：pengding ---> rejected 抛出错误,从而进入该函数进行处理
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 每页展示条数
    sizeChangeHandler(size) {
      this.pageSize = size;
    },
    // 跳转页
    currentChangeHandler(page) {
      this.currentPage = page;
    },
    // 导出Excel事件
    handlerDownloadALL() {
      const tableData = [
        [
          "商品编号",
          "下单时间",
          "商品标题",
          "用户名",
          "电话",
          "地址",
          "金额",
          "支付方式",
          "支付状态",
          "物流公司",
          "快递单号",
          "物流状态"
        ]
      ];
      this.orderList.forEach(item => {
        const rowData = [
          item.id,
          item.time,
          item.goodsInfo.title,
          item.userInfo.username,
          item.userInfo.tel.toString(),
          item.userInfo.address,
          item.payInfo.money,
          item.payInfo.method,
          item.payInfo.isPay,
          item.logisticsInfo.type,
          item.logisticsInfo.id,
          item.logisticsInfo.status
        ];
        tableData.push(rowData);
      });
      const ws = Xlsx.utils.aoa_to_sheet(tableData);
      const wb = Xlsx.utils.book_new();
      const date = new Date();
      Xlsx.utils.book_append_sheet(wb, ws, "订单数据"); // 工作簿名称
      Xlsx.writeFile(wb, `订单数据${date.toLocaleString()}.xlsx`); // 保存的文件名
    },
    // 清空搜索框,恢复全部订单列表
    inputClearHandler() {},
    // 回车搜索
    inputKeyupHandler() {
      this.searchHandler();
    },
    // 搜索按钮搜索
    searchClickHandler() {
      this.searchHandler();
    },
    // 搜索事件
    searchHandler() {
      // 每次搜索时,先将当前数组还原为原始数据
      this.orderList = [...this.oldOrderList];
      // 如果搜索框内容为空,不搜索
      if (!this.value) return;
      // 再在当前数据中的每一项的search属性的值中筛选输入框的内容
      // 并且改变渲染数据,呈现出筛选结果,所以上面需要保存原始数据
      this.orderList = this.orderList.filter(
        item => item.search.indexOf(this.value) !== -1
      );
    },
    // 批量删除
    batchDeleteHandler() {
      this.$confirm("尚未开发", "提示", {
        type: "error"
      })
        .then(() => {
          // this.$message()
        })
        .catch(() => {});
    }
  }
};
</script>
<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}

.order-text {
  font-size: 12px;
  text-align: center;
}

.el-form-item {
  margin: 0;
}

.el-button {
  white-space: normal;
}
</style>
